import React, { Component } from 'react'
import {Col, Icon, message, Row, Tabs, Tag} from 'antd'
import { STATUS } from '../../constant/homework-request-status'
import '../../less/index.less'
import { TwsReactMarkdownPreview } from 'tws-antd'
import { STUDENT_MODIFY_ASSIGNMENT_STATUS } from '../../constant/notification-status'
import { convertContent } from '../../constant/lang-util'
import AnswerSubmitBox from '../common/answer-submit-box'
import AnswerSubmitZipBox from '../common/answer-submit-zip-box'
import { FormattedMessage } from 'react-intl'
import QuizSuggestionBox from '../common/quiz-suggestion-box'
import QuizNoteModal from "./quiz-note-modal";

const TabPane = Tabs.TabPane

export default class HomeworkQuiz extends Component {
  constructor (props) {
    super(props)
    this.state = {
      userAnswerRepo: props.quiz.userAnswer,
      userAnswerZip: props.quiz.userAnswerZipUrl,
      branch: props.quiz.answerBranch,
      loading: false,
      submissionId: 0,
      isQuizNoteModalVisible: false,
      noteContent: ''
    }
  }

  componentDidMount () {
    const {studentId, assignmentId, quiz} = this.props
    if (this.needRunScript()) {
      this.props.getRunningLogs(studentId, assignmentId, quiz.id)
    }
  }
  buildSubmitData (userAnswerRepo, branch) {
    const {assignmentId, quiz, studentId, taskId} = this.props
    return {
      assignmentId,
      quizId: quiz.id,
      taskId,
      userAnswerRepo,
      branch,
      studentId
    }
  }

  buildNotification () {
    const {quiz, assignmentId, programId, studentId, taskId} = this.props
    return {
      receiverId: studentId,
      programId,
      taskId,
      assignmentId,
      quizId: quiz.id,
      type: STUDENT_MODIFY_ASSIGNMENT_STATUS,
      appType: 'simpleCodingQuiz'
    }
  }

  submit () {
    const {userAnswerRepo, branch} = this.state
    const reg = new RegExp('^((http|https)://)*?(www.)*?(git).*?$')
    const url = userAnswerRepo || ''
    const defaultBranch = branch || 'master'
    if (!reg.test(url)) {
      message.info(convertContent('请输入正确的git仓库地址'))
      return
    }
    this.submitAnswer(userAnswerRepo, defaultBranch)
  }

  needRunScript () {
    const {quiz} = this.props
    return !!quiz.evaluateScript
  }

  getStudentAnswer () {
    if (this.needRunScript()) {
      return this.props.submission.status === STATUS.SUCCESS
        ? <Tag color='#87d068'>{convertContent('编译通过')}</Tag>
        : <Tag color='red'>{convertContent('编译不通过')}</Tag>
    }
    return <Tag color='green'>{convertContent('已提交')}</Tag>
  }
  loadLogs () {
    const {submission, assignmentId, quiz, studentId} = this.props
    if (submission.status === STATUS.ERROR) {
      message.warning(convertContent('编译不通过'))
      this.setState({loading: false})
      return
    }
    if (submission.status === STATUS.SUCCESS) {
      message.success(convertContent('编译通过'))
      this.props.getHomeworkQuizzes(assignmentId)
      this.setState({loading: false})
      return
    }
    this.props.getRunningLogs(studentId, assignmentId, quiz.id)
    window.setTimeout(() => this.loadLogs(), 1500)
  }

  getRunningResult () {
    const {submission = {}} = this.props

    const result = submission.status
      ? <Tag color={submission.status === STATUS.ERROR ? 'red' : '#87d068'}>
        {convertContent(submission.status === STATUS.ERROR ? '失败' : '通过')}
      </Tag>
      : <Tag color='gold'><Icon type='sync' spin /><FormattedMessage id='进行中' /></Tag>

    return (<div className={submission.id ? '' : 'hidden'}>
      <p className='margin-t-1'>{result}</p>
      <div className='result-content'>
        {submission.jobMessage}
      </div>
    </div>)
  }

  submitAnswer (userAnswerRepo, defaultBranch) {
    const notification = this.buildNotification()
    const data = this.buildSubmitData(userAnswerRepo, defaultBranch)
    this.props.submitAnswer(data, () => {
      message.success(convertContent('答案提交成功'))
      if (this.needRunScript()) {
        this.setState({loading: true})
        this.loadLogs()
      }
      this.props.addNotification(notification)
    })
  }
  setUserAnswerRepo (userAnswerRepo) {
    this.setState({userAnswerRepo: userAnswerRepo.trim()})
  }
  setBranch (branch) {
    this.setState({branch: branch.trim()})
  }

  showModal = () => {
    this.setState({
      isQuizNoteModalVisible: true,
    });
  };

  handleOk = () => {
    this.setState({
      isQuizNoteModalVisible: false,
      noteContent: ''
    });
    this.handleSubmit()
  };

  handleCancel = () => {
    this.setState({
      isQuizNoteModalVisible: false,
    });
  };

  handleSubmit = () => {
    const {noteContent} = this.state
    const {programId, assignmentId, studentId, quiz, taskId, user} = this.props
    const quizId = quiz.id
    const tutorId = user.id
    const quizType = 'SIMPLE_CODING_QUIZ'
    const values = {programId, taskId, assignmentId, quizId, studentId, tutorId, quizType, noteContent}
    this.props.submitNote(values)
  };

  handelChangeNote(value) {
    this.setState({
      noteContent: value
    })
  }

  render () {
    const {loading, userAnswerRepo, userAnswerZip, branch, submission, preview, isQuizNoteModalVisible} = this.state
    const {quiz, reviewQuiz,settings} = this.props
    const {id, createTime, supplementTime} = reviewQuiz
    const {userAnswer, userAnswerZipUrl} = quiz
    const isFinished = userAnswer !== '' || userAnswerZipUrl !== ''

    return <div>
      <div className='margin-t-3'>
        <h3><FormattedMessage id='作业内容' /></h3>
        <div className='margin-t-2 mark-down-wrap'>
          <TwsReactMarkdownPreview source={quiz ? quiz.description : ''} />
          {this.props.isTutor
          ?<h4><br/><FormattedMessage id='git仓库地址' />：<a target='_blank' href={quiz ? quiz.templateRepository : ''}>{quiz ? quiz.templateRepository : ''}</a></h4>: ''}
        </div>
        <QuizSuggestionBox
          settings={settings}
          quiz={quiz}
          submit={this.props.submitQuizSuggestion}
        />
      </div>

      <div className='margin-t-3'>
        {
          this.props.isTutor
            ? <div>
                <Row>
                  <Col span={2}>
                    <h3><FormattedMessage id='学生答案'/></h3>
                  </Col>
                  <Col span={3}>
                    {
                      reviewQuiz.id !== null ? <a onClick={this.showModal}><FormattedMessage id='添加备忘录'/></a> : ''
                    }
                    <QuizNoteModal
                        isQuizNoteModalVisible={isQuizNoteModalVisible}
                        handleOk={this.handleOk}
                        handleCancel={this.handleCancel}
                        handelChangeNote={this.handelChangeNote.bind(this)}
                    />
                  </Col>
                </Row>
                {
                  supplementTime
                    ? <span className='submit-time-box'>
                      <Icon type='clock-circle' />
                      {supplementTime}
                    </span>
                    : ''
                }
                <br />
                {
                  isFinished
                    ? this.getStudentAnswer()
                    : ''
                }
              <div className='margin-t-2 mark-down-wrap'>
                {
                  isFinished
                    ? <div>
                      <h4><FormattedMessage id='答案分支' />：{quiz.answerBranch}</h4><br/>
                      <TwsReactMarkdownPreview source={quiz.userAnswer || quiz.userAnswerZipUrl} />
                    </div>
                    : <FormattedMessage id='学生还没有提交答案' />
                }
              </div>
            </div>
          : <div>
            <h3><FormattedMessage id='我的答案' /></h3>
            {
              id
                ? <span className='submit-time-box'>
                  <Icon type='clock-circle' />
                  {createTime}
                </span>
                : ''
              }
            <Tabs defaultActiveKey='1'>
              <TabPane tab={<FormattedMessage id='提交仓库地址' />} key='1'>
                <AnswerSubmitBox
                  loading={loading}
                  userAnswerRepo={userAnswerRepo}
                  branch={branch}
                  quiz={quiz}
                  submission={submission}
                  preview={preview}
                  needRunScript={this.needRunScript.bind(this)}
                  getRunningResult={this.getRunningResult.bind(this)}
                  submit={this.submit.bind(this)}
                  setUserAnswerRepo={this.setUserAnswerRepo.bind(this)}
                  setBranch={this.setBranch.bind(this)}
                />
              </TabPane>
              <TabPane tab={<FormattedMessage id='提交压缩包' />} key='2' >
                <AnswerSubmitZipBox
                  userAnswerZipUrl={userAnswerZip}
                  submitAnswer={this.submitAnswer.bind(this)}
                  needRunScript={this.needRunScript.bind(this)}
                  getRunningResult={this.getRunningResult.bind(this)}
                />
              </TabPane>
            </Tabs>
          </div>
        }
      </div>
    </div>
  }
}
